/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.file.service.impl;

import me.zhengjie.modules.file.domain.File;
import me.zhengjie.modules.file.service.dto.FileOwnModel;
import me.zhengjie.modules.file.service.dto.FilePublicModel;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.file.repository.FileRepository;
import me.zhengjie.modules.file.service.FileService;
import me.zhengjie.modules.file.service.dto.FileDto;
import me.zhengjie.modules.file.service.dto.FileQueryCriteria;
import me.zhengjie.modules.file.service.mapstruct.FileMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;

import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author FireWork
* @date 2021-04-02
**/
@Service("fileService")
@RequiredArgsConstructor
public class FileServiceImpl implements FileService {

    private final FileRepository fileRepository;
    private final FileMapper fileMapper;

    @Override
    public Map<String,Object> queryAll(FileQueryCriteria criteria, Pageable pageable){
        Page<File> page = fileRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(fileMapper::toDto));
    }

    @Override
    public List<FileDto> queryAll(FileQueryCriteria criteria){
        return fileMapper.toDto(fileRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public FileDto findById(Integer id) {
        File file = fileRepository.findById(id).orElseGet(() -> new File());
        ValidationUtil.isNull(file.getId(),"File","id",id);
        return fileMapper.toDto(file);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FileDto create(File resources) {
        return fileMapper.toDto(fileRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(File resources) {
        File file = fileRepository.findById(resources.getId()).orElseGet(() -> new File());
        ValidationUtil.isNull( file.getId(),"File","id",resources.getId());
        file.copy(resources);
        fileRepository.save(file);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            fileRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<FileDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (FileDto file : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("文件名", file.getFileName());
            map.put("文件地址", file.getFilePath());
            map.put(" userId",  file.getUserId());
            map.put("可查看用户", file.getAudienceId());
            map.put("创建时间", file.getCreateTime());
            map.put("是否公开", file.getIsPublic());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
    @Override
    public Page<FilePublicModel> findPublicFile(Pageable pageable){
        return fileRepository.findPublicFile(pageable);
    }

    @Override
    public Page<FileOwnModel> findOwnFile(Integer loginId, Pageable pageable) {
        return fileRepository.findOwnFile(loginId, pageable);
    }

    @Override
    public Page<Object[]> findAdminFile(Pageable pageable) {
        return fileRepository.findAdminFile(pageable);
    }

    @Override
    public Map verifyFileDownload(Integer loginId,Integer fId) {
        Object[] objects= (Object[]) fileRepository.verifyFileDownload(loginId,fId);
        Map<String,String> map=new HashMap<>();
        if(objects!=null){
            map.put("id",objects[0].toString());
            map.put("name",objects[1].toString());
            map.put("path",objects[2].toString());
        }
        return map;
    }


}
